﻿<?php
	ini_set('date.timezone','Asia/Shanghai');
	require 'query.php';
	// $_address = $_GET['address'];
	// $_link = $_GET['link'];
	/*
	if(!generate('air','http://air-software.top')) {
		echo 'ok';
	}
	*/
	// generate($_address);
	function getIP() {
		global $ip;
		if (getenv("HTTP_CLIENT_IP")) 
			$ip = getenv("HTTP_CLIENT_IP"); 
			else if(getenv("HTTP_X_FORWARDED_FOR")) 
			$ip = getenv("HTTP_X_FORWARDED_FOR"); 
			else if(getenv("REMOTE_ADDR")) 
			$ip = getenv("REMOTE_ADDR"); 
			else 
			$ip = "Unknown"; 
			return $ip; 
	}
	
	function generate($_address,$_link) { // 返回true成功, false失败
		/*
		$status = $_COOKIE['!expire'];
		if($status == 'false') {
			return 5;
		} else {
		*/
		if($_address == '' or $_address == null or $_link == '' or $_link == null) {
			// echo 'var result = 4;'; // Empty address
			return 3;
		} else {
			if($_address == 'air' or $_address == 'css' or $_address == 'fonts' or $_address == 'example' or $_address == 'js' or $_address == 'font' or $_address == 'require' or $_address == 'requires' or $_address == 'pictures' or $_address == 'picture' or $_address == 'sitemap' or $_address == 'sitemaps') {
				// echo 'var result = 2;'; // System reserved
				return 2;
			} else {
				$result = query($_address); // false=不存在, true=存在
				if($result == false) {
					// echo '请稍候,正在生成中<br>';
					// echo $result;
					if(!mkdir($_address)) {
						// echo 'var result = 5;'; // Failed
						return null; // Unknown error(s)
					} else {
						$text = '<html><head><script language="javascript" type="text/javascript">window.location.href="';
						$text2 = $_link . '";</script></head></html>';
						$text3 = $text . $text2;
						$file = fopen($_address . '/index.html','w');
						fwrite($file, $text3);
						fclose($file);
						// echo 'var result = 0;'; // OK
						$log = fopen('events.log','a');
						$_log = '
[' . getIP() . ']
time=' . date('M dS Y H:i',time()) . '
address=' . $_address . '
link=' . $_link . '
';
						fwrite($log,$_log);
						fclose($log);
						return 0;
					}
				} else {
					// echo '链接已存在<br>';
					// echo 'var result = 1;'; // Link already exists
					return 1;
				}
			}
		}
	}
?>